using System;
using UnityEngine;

public class Entity_Combat : MonoBehaviour
{
    public event Action<float> OnDoingPhysicalDamage = delegate { };
    [SerializeField] private Transform targetCheck;
    [SerializeField] private float targetDetectRadius;
    [SerializeField] private LayerMask targetLayer;
    private Entity_Stat stats;
    private Entity_SFX entitySFX;

    [Header("Staus Effect Details")]

    [SerializeField] private DamageScaleData baseAttackScaleData;
    private AttackData attackData;
    void Awake()
    {
        stats = GetComponent<Entity_Stat>();
        entitySFX = GetComponent<Entity_SFX>();
    }

    //执行攻击
    public void PerformAllAttack()
    {
        bool targetGotHit = false;
        //遍历检测到的攻击目标
        foreach (var attackTarget in GetDetectedColliders(targetLayer))
        {
            targetGotHit = PerformAttack(attackTarget.transform);
        }
        if (targetGotHit == false)
            entitySFX?.PlayAttackMiss();
    }

    public bool PerformAttack(Transform attackTarget)
    {
        //定义接口，得到所有实现接口的攻击对象
        IDamagable damagable = attackTarget.GetComponent<IDamagable>();
        if (damagable == null)
            return false;

        attackData = stats.GetAttackData(baseAttackScaleData);

        Entity_StatHandler targetStatHandler = attackTarget.GetComponent<Entity_StatHandler>();
        Entity_VFX entityVFX = attackTarget.GetComponent<Entity_VFX>();

        //计算物理伤害
        float physicalDamage = attackData.physicalDamage;
        //计算化学伤害
        float elementalDamage = attackData.elementalDamage;
        ElementType elementType = attackData.elementType;

        bool targetGotHit = damagable.TakeDamage(physicalDamage, elementalDamage, elementType, transform, attackData.isCrit);

        if (elementType != ElementType.None)
            targetStatHandler?.ApplyStatusEffect(elementType, attackData.effectData);

        if (targetGotHit)
        {
            //特效处理
            entityVFX.EffectHandler(transform, attackData.isCrit, elementType);
            OnDoingPhysicalDamage(physicalDamage);
            entitySFX?.PlayAttackHit();
        }
        return true;
    }

    //得到所以检测到的攻击对象
    protected Collider2D[] GetDetectedColliders(LayerMask targetCheckLayer) => Physics2D.OverlapCircleAll(targetCheck.position, targetDetectRadius, targetCheckLayer);
    private void OnDrawGizmos()
    {
        Gizmos.color = Color.green;
        Gizmos.DrawWireSphere(targetCheck.position, targetDetectRadius);
    }
}
